﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Reflection;

namespace CSF.Utility.Misc
{
    public static class ObjectExtensions
    {
        /// <summary>
        /// 将一个匿名类转换成字典类
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static Dictionary<string, object> ToDictionary(this object obj)
        {
            var result = new Dictionary<string, object>();
            var properties = TypeDescriptor.GetProperties(obj);
            foreach (PropertyDescriptor property in properties)
            {
                object val = property.GetValue(obj);
                result.Add(property.Name, val);
            }
            return result;
        }

        public static TBase ShadowCopy<TBase, TChild>(this TChild obj)
            where TChild : TBase where TBase : new()
        {
            TBase result = new TBase();
            Type t = typeof(TBase);
            var props = t.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetField | BindingFlags.SetProperty);
            foreach (var prop in props)
            {
                prop.SetValue(result, prop.GetValue(obj, null), null);
            }
            return result;
        }

        public static TChild ShadowCopy<TBase, TChild>(this TBase obj)
            where TChild : TBase, new()
        {
            TChild result = new TChild();
            Type t = typeof(TBase);
            var props = t.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetField | BindingFlags.SetProperty);
            foreach (var prop in props)
            {
                prop.SetValue(result, prop.GetValue(obj, null), null);
            }
            return result;
        }
    }
}
